package edu.tms.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;

import edu.tms.bean.*;
import edu.tms.dao.*;
import net.easymvc.annotation.Encoding;
import net.easymvc.annotation.FilePath;
import net.easymvc.annotation.FormData;
import net.easymvc.annotation.Param;
import net.easymvc.core.Action;


/**
 * 学生Action
 * @author Administrator
 *
 */
public class StudentAction extends Action{
	/**
	 * 提交评测
	 */
	public String subEvaluating(
			@Param("teacherid")Integer tchid,
			@Param("assid") Integer asid,
			Evaluating evaluating){		
		User u=(User)getSession("curUser");//获取当前用户的用户Id
		evaluating.setStuId(u.getUserId());//用户的ID
		evaluating.setAssessmentId(tchid);//被评测的老师的Id
		evaluating.setAssessmentId(asid);
		evaluating.setCreateTime(new Date());//设置提交评测的时间
		EvaluatingDaoImp edao =new EvaluatingDaoImp();//设置dao的工具
		try {
			edao.save(evaluating);//保存操作
		} catch (Exception e) {
			System.out.println("存储失败");//报错回馈
			e.printStackTrace();
		}
		return "/s/pingce.jsp";
	}
	
	/**
	 * 展示评测（针对那个科目老师，以及展示评测的时间段）
	 * @throws Exception 
	 */
	@Encoding(value = "utf-8")
	public String evaluatinInfo(@Param("wancheng")Integer stateid){
		AssessmentInfoDaoImp amdao =new AssessmentInfoDaoImp();//创建一个测评信息dao用于执行查询操作
		EvaluatingDaoImp edao=new EvaluatingDaoImp();
		User u=(User)getSession("curUser");//获取当前用户的用户Id
		try {
			Long a=edao.selectinfo(u.getUserId());	
			if(a!=0){
				setRequest("isok", 1);
				return "/s/pingce.jsp";
			}else{
				setRequest("isok", 0);
				AssessmentInfo as=new AssessmentInfo();//创建一个测评信息表
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");//创建一个时间格式设置器
//				as2=amdao.findAll(1, 1);//用测评信息dao进行数据查询，（查询方法修改为单条倒叙查询详细见dao）
//				as=as2.get(0);//将获取到的第一条数据进行封装到测评信息类里面（由于list不能直接用户传输给网页所以用类封装）
				as = amdao.findAssess(u.getUserId());
				if(as == null) setRequest("error_msg", "信息获取失败");
				setRequest("formPc",as);//数据传递
				setRequest("time",sdf.format(as.getAssessmentStartTime()));//将获取到的开始时间进行格式设置并传递
				setRequest("timer",sdf.format(as.getAssessmentEndTime()));//将获取到的结束时间进行格式设置并传递
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return "/s/pingce.jsp";
	}
	
	/**
	 * 学生考试成绩查询
	 * @param pageNo
	 * @param content
	 * @return
	 */
	@Encoding("UTF-8")
	public String countScore(@Param("pageNo")Integer pageNo,
			@Param("content")Integer content){
		User user = (User) getSession("curUser");
		if(user == null)return "redirect:/login.html";
		if(pageNo == null||pageNo <= 0) pageNo=1;//页码
		ExamDaoImp eDao=new ExamDaoImp();
		ExamTypeDaoImp etDao=new ExamTypeDaoImp();
		int pages=0;//总页数
		//查询考试类型
		List<ExamType> examtype;
		try {
			examtype=etDao.findAll();
			if(content==null || content==0||content==1){
				//专业课
				pages=(int) eDao.queryAllPages(user.getUserId(),examtype.get(1).getExamTypeName(),10);
			}else if(content==2){
				//学历科
				pages=(int) eDao.queryAllPages(user.getUserId(),examtype.get(0).getExamTypeName(),10);
			}else if(content==3){
				//省考
				pages=(int) eDao.queryAllPages(user.getUserId(),examtype.get(2).getExamTypeName(),10);
			}else if(content==4){
				//统考
				pages=(int) eDao.queryAllPages(user.getUserId(),examtype.get(3).getExamTypeName(),10);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "error,jsp";
		}
		if(pageNo>pages)pageNo=pages;
		if(pageNo<=0)pageNo=1;
		try {
			List<Exam> exams = null;
			if(content==null || content==0||content==1){
				//专业课
				exams=eDao.queryAllExam(user.getUserId(),examtype.get(1).getExamTypeName(),pageNo,10);
			}else if(content==2){
				//学历课
				exams=eDao.queryAllExam(user.getUserId(),examtype.get(0).getExamTypeName(),pageNo,10);
			}else if(content==3){
				//省考
				exams=eDao.queryAllExam(user.getUserId(),examtype.get(2).getExamTypeName(),pageNo,10);
			}else if(content==4){
				//统考
				exams=eDao.queryAllExam(user.getUserId(),examtype.get(3).getExamTypeName(),pageNo,10);
			}
			String exam=JSON.toJSONString(exams);
			String json="{\"exam\":"+exam+",\"pageNo\":\""+pageNo+"\","+"\"pages\":\""+pages+"\"}";
			return "ajax:"+json;
		} catch (Exception e) {
			e.printStackTrace();
			return "error.jsp";
		}
	}
	
	@Encoding("utf-8")
	//通过学生编号来查询学生的课程考勤
	public String stuAttendance(@Param("pageNo") Integer pageNo){
		User user =(User) getSession("curUser");
		if(user == null) return "redirect:/login.html";
		CourseAttendanceDaoImp caddao=new CourseAttendanceDaoImp();
		if(pageNo == null || pageNo < 1) pageNo = 1;
		try {
			List<CourseAttendance> list =caddao.findAll(user.getUserId(),pageNo,10);
			int pages=(int) caddao.findAll(pageNo);
			if( pageNo > pages && pages > 1) pageNo = pages;
			setRequest("pageNo", pageNo);
			setRequest("pages", pages);
			setRequest("mas", list);
			return "/s/classAttendance.jsp";
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}
	//通过学生的寝室名称来查询寝室考勤情况
	public String dorm(@Param("pageNo") Integer pageNo){
		User user =(User) getSession("curUser");
		if(user == null) return "redirect:/login.html";
		DormCheckDaoImp dcdao=new DormCheckDaoImp();
		if(pageNo == null || pageNo < 1) pageNo = 1;
		try {
			String dormname = dcdao.getDormName(user.getUserId());
			List<DormCheck> list = dcdao.findAll(dormname, pageNo, PAGE_SIZE);
			int pages = (int) dcdao.getPages(dormname, PAGE_SIZE);
			if( pageNo > pages && pages > 1) pageNo = pages;
			setRequest("pageNo", pageNo);
			setRequest("pages", pages);
			setRequest("dorm",list);
			return "/s/bedroom.jsp";
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	
	/**
	 * 校园历程
	 */
	@Encoding("utf-8")
	public String schoolLife() {
		SchoolLifeDaoImp lifeDao=new SchoolLifeDaoImp();
		try {
			//查询校园历程传到网页
			List<SchoolLife> lifeList = lifeDao.findByid(1, 1, 5);
			setSession("lifeList", lifeList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/s/course.jsp";
	}
	/**
	 * 校园历程加载更多
	 * @param pageNo
	 * @return
	 */
	public String lifeMore(@Param("page") Integer pageNo){
		User user=(User)getSession("curUser");
		Integer star=(pageNo-1)*1;
		SchoolLifeDaoImp lifeDao=new SchoolLifeDaoImp();
		try {
			//查询校园历程传到网页
			List<SchoolLife> lifeList=lifeDao.findByid(user.getUserId(), star,star+1);
			setRequest("lifeList", lifeList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/s/iframe.jsp";
	}
	/**
	 * 校园历程内容
	 * @return
	 */
	@Encoding("utf-8")
	public String lifeContent(
			@Param("title")String activityTitle,
			@Param("content")String schoolLifeContent,
			@Param("albumid")String albumId){
		PictureDaoImp pDao=new PictureDaoImp();
		if(albumId!=null){
			try {
				List<Picture> pList=pDao.findUrl(albumId);//查询校园历程内容
				String listJson = JSON.toJSONString(pList);//转成json数据
				listJson = "{\"pList\":["+listJson+"],"+"\"at\":\""+activityTitle+"\","+"\"slc\":\""+schoolLifeContent+"\"}";
				return "ajax:"+listJson;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "/s/course.jsp";
	}
	
	/**
	 * 班级活动
	 */
	@Encoding("utf-8")
	public String classActive() {
		ClassActivityDaoImp caDao=new ClassActivityDaoImp();
		try {
			//查询活动
			List<ClassActivity> calist=caDao.findAll(1,1,5);
			setSession("calist",calist);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/s/activiti.jsp";
	}
	
	/**
	 * 班级活动加载更多
	 * @param pageNo
	 * @return
	 */
	public String activeMore(@Param("page") Integer pageNo){
		User user=(User)getSession("curUser");
		ClassActivityDaoImp caDao=new ClassActivityDaoImp();
		Integer star=(pageNo-1)*2;
		try {
			//查询校园历程传到网页
			List<ClassActivity> calist=caDao.findAllByStuid(user.getUserId(),star,2);
			setRequest("calist", calist);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/s/iframe2.jsp";
	}
	
	/**
	 * 班级活动内容
	 * @return
	 */
	@Encoding("utf-8")
	public String ActiveContent(@Param("title")String activityTitle,
			@Param("content")String schoolLifeContent,
			@Param("albumid")String albumId,
			@Param("classActivityId")String activityId){
		PictureDaoImp pDao=new PictureDaoImp();
		if(albumId!=null){
			try {
				//查询活动内容
				List<Picture> pList= pDao.findUrl(albumId);
				String listJson = JSON.toJSONString(pList);
				listJson = "{\"pList\":["+listJson+"],"+"\"at\":\""+activityTitle+"\","+"\"slc\":\""+schoolLifeContent+"\","+"\"aid\":\""+activityId+"\"}";
				return "ajax:"+listJson;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "/s/activiti.jsp";
	}
	/**
	 * 活动报名
	 * @return
	 */
	@Encoding("utf-8")
	public String showSign(@Param("aid")Integer activityId){
		User user=(User)getSession("curUser");
		if(user == null) return "redirect:/login.html";
		ActivityEnrollDaoImp enrollDao = new ActivityEnrollDaoImp();
		String mess=null;
		try {
			//查询这个用户是否已经报名
			ActivityEnroll act=enrollDao.findByUid(user.getUserId(),activityId);
			if(act != null){//此用户已报名
				mess="1";
			}else{
				ActivityEnroll enrll=new ActivityEnroll();//活动报名实体
				enrll.setStuId(user.getUserId());
				enrll.setClassActivityId(activityId);
				enrll.setCreateTime(new Date());
				enrll.setEnrollState(1);
				enrollDao.save(enrll);
				mess="2";
			}
			return "ajax:"+"{\"mess\":\""+mess+"\"}";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/s/info.jsp";
	}
	
	
	/**
	 * 查询小组信息
	 * @return
	 */
	@Encoding("utf-8")
	public String squad() {
		User user = (User) getSession("curUser");
		if(user == null) return "redirect:/login.html";
		StudentDaoImp dao = new StudentDaoImp();
		SquadDaoImp sq=new SquadDaoImp();
		try {
			//查询所在小组id
			long squadId = dao.getSquadId(user.getUserId());
			//查询所在小组信息
			Squad squad = sq.findBySquadId(squadId);
			//查询组长信息
			Student leader = dao.getLeader(squad.getSquadLeader());
			//查询小组其他成员
			List<Student> other = dao.getSquadMember(squadId);
			if(squad.getSquadName() == null || leader == null || other == null || other.size() == 0){
				setRequest("error_msg", "信息获取失败，请重试");
			}
			setRequest("leader", leader);
			setRequest("other", other);
			setRequest("squadName", squad.getSquadName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/s/team.jsp";
	}
	
	/**
	 * 查询班级财务
	 * @return
	 */
	@Encoding("utf-8")
	public String classfee(@Param("pageNo") Integer pageNo){
		User user = (User) getSession("curUser");
		if(user == null)return "redirect:/login.html";
		if(pageNo == null || pageNo < 1) pageNo = 1;
		StudentDaoImp stuDao = new StudentDaoImp();
		ClassFeeDaoImpl dao = new ClassFeeDaoImpl();
		try {
			//获取学生活委员所在的班级id
			int classId = stuDao.getClassId(user.getUserId());
			int pages = (int) dao.getCount(classId,10);
			if( pageNo > pages && pages > 1) pageNo = pages;
			//通过班级id获取生活委员所在的班级的收支明细
			List<ClassFee> list = dao.findByClassId(classId, pageNo, PAGE_SIZE);
			setRequest("classfees", list);
			setRequest("pageNo", pageNo);
			setRequest("pages", pages);
			return "/s/moneyinfo.jsp";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/s/moneyinfo.jsp";
	}
	
	/**
	 * 学生:查询所有已布置作业
	 * @param stuClassName 获取学生所在班级名称
	 * @return 至显示网页
	 */
	@Encoding("UTF-8")
	public String assign(
			@Param("pageNo") Integer pageNo,
			@Param("content") String content){
		User user = (User) getSession("curUser");
		if(user == null)return "redirect:/login.html";
		if(pageNo == null || pageNo <= 0 ) pageNo=1;
		long pages = 0;
		//创建HomeworkDaoImp对象
		HomeworkDaoImp h=new HomeworkDaoImp();
		WorkSubmitDaoImp ws=new WorkSubmitDaoImp();
		StudentDaoImp stuDao = new StudentDaoImp();
		try {
			String className = stuDao.getClassName(user.getUserId());
			if(className == null){
				setRequest("error_msg", "信息获取错误请重试");
				return "/s/work.jsp";
			}
			List<Homework> hws;
			if(content==null || content.length()==0){
				//通过班级名称查询该班级所有作业
				hws=h.findAll(className, pageNo, PAGE_SIZE);
				pages = h.selectPage(PAGE_SIZE, className);
				if(pageNo > (int)pages) pageNo=(int) pages;
			}else{
				//通过老师姓名或科目查询该班级所有作业
				hws=h.findAll(className,content, pageNo, PAGE_SIZE);
				pages=h.selectPage(PAGE_SIZE, className,content);
				if(pageNo > (int)pages) pageNo=(int) pages;
			}
			//查询该学生是否已提交作业
			for (int i = 0; i < hws.size(); i++) {
				Homework hw = hws.get(i);
				hw.setFulfilState(ws.checkWork(hw.getHomeworkId(), user.getUserId()));
			}
			//发送数据
			setRequest("pageNo", pageNo);
			setRequest("pages", pages);
			setRequest("hws", hws);
			return "/s/work.jsp";
		} catch (Exception e) {
			e.printStackTrace();
			return "/error.jsp";
		}
	}
	/**
	 * 
	 * 学生:查询已提交作业
	 * @param stuId 获取学生编号
	 * @return 至显示网页
	 */
	@Encoding("UTF-8")
	public String submission(
			@Param("pageNo") Integer pageNo,
			@Param("content") String content){
		User user = (User) getSession("curUser");
		if(user == null) return "redirect:/login.html";
		if(pageNo == null || pageNo <= 0) pageNo=1;
		long pages = 0;//总页数
		//创建StudentWorkDaoImp对象
		WorkQualityDaoImp wqDao=new WorkQualityDaoImp(); 
		try {
			List<WorkQuality> workQua;
			if(content==null || content.length()==0){
				//通过学生编号查询该学生已提交所有作业
				workQua=wqDao.findAll(user.getUserId(), pageNo, PAGE_SIZE);
				pages=wqDao.selectPage(PAGE_SIZE, user.getUserId());
			}else{
				pages=wqDao.selectPage(PAGE_SIZE, user.getUserId(),content);
				//通过学生编号查询该学生已提交所有作业
				workQua=wqDao.findAll(user.getUserId(),content, pageNo, PAGE_SIZE);
			}
			//发送数据
			setRequest("pageNo", pageNo);
			setRequest("pages", pages);
			setRequest("hms", workQua);
			return "/s/submittedwork.jsp";
		} catch (Exception e) {
			e.printStackTrace();
			return "/error.jsp";
		}
	}
	/**
	 * 学生:提交作业
	 * @param content 提交内容
	 * @param file 上传文件
	 * @return
	 */
	@FormData
	@Encoding("UTF-8")
	public String submitWork(WorkSubmit work,
							@FilePath String workFile){
		User user = (User) getSession("curUser");
		if(user == null) return "redirect:/login.html";
		WorkSubmitDaoImp ws=new WorkSubmitDaoImp();
		work.setStuId(user.getUserId());
		work.setCreateTime(new Date());
		work.setWorkState(1);
		work.setWorkFile(workFile);
		try {
			if(ws.save(work) == 0) setRequest("error_msg", "信息上传错误，请重试");
			return "redirect:/student/assign.do";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/student/assign.do";
	}
	
	
	//学生显示个人信息方法
	@Encoding("utf-8")
	public String stuInfo(){
		User user = (User) getSession("curUser");
		if(user == null)return "redirect:/login.html";
		//学生dao
		StudentDaoImp dao=new StudentDaoImp();
		try {
			//根据id查找学生信息
			Student stu = dao.findByKey(user.getUserId());
			if(stu == null) setRequest("error_msg", "信息出错请重试");
			//转发到网页中
			setRequest("stu", stu);
			//返回到网页
			return "/s/basicinfo.jsp";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/s/basicinfo.jsp";
	}
	
	//学生显示个人缴费情况
	@Encoding("utf-8")
	public String stuTuition(
			@Param("pageNo")Integer pageNo){
		User user = (User) getSession("curUser");
		if(user == null)return "redirect:/login.html";
		if(pageNo == null || pageNo < 1) pageNo = 1;
		//个人缴费dao
		TuitionDaoImp dao=new TuitionDaoImp();
		try {
			//查询总页数
			long count = dao.getCount(user.getUserId(),PAGE_SIZE);
			List<Tuition> list=dao.findAll(user.getUserId(), pageNo, PAGE_SIZE);
			if(list == null) setRequest("error_msg", "信息出错请重试");
			//转发到网页中
			setRequest("pageNo",pageNo);
			setRequest("list", list);
			setRequest("pages", count);
			//返回到网页
			return "/s/personalfinance.jsp";
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
}
